const fetch = require('../../request/fetch')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        nameVal: '', //姓名
        studentVal: "", //学号
        platform: '', // 登录设备
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 登录设备
        const that = this
        wx.getSystemInfo({
            success(res) {
                that.setData({
                    platform: res.platform
                })
            }
        })
    },
    onShow(){
        wx.hideHomeButton()
    },
    // 获取学生的名字
    userNameFn(e) {
        let val = e.detail.value.trim()
        this.setData({
            nameVal: val
        })
    },
    // 获取学号
    studentFn(e) {
        let num = e.detail.value.trim()
        this.setData({
            studentVal: num
        })
    },
    // 登录按钮
    loginFn() {
        const that = this
        if (that.data.nameVal == '' || that.data.studentVal == '') {
            wx.showToast({
                title: '名字和学号不能为空',
                icon: 'none',
                duration: 2000
            })
        } else {
                    // 发起请求
                    fetch.loginFn({
                        data: {
                            "name": that.data.nameVal,
                            "sno": that.data.studentVal,
                            "platform": that.data.platform
                        }
                    }).then(res => {
                        if(res.message=='登录失败'){
                            wx.showToast({
                              title: '登录失败',
                              icon: 'none',
                              duration: 2000,
                            })
                        }else{
                            let token = res.data.accessToken
                            let user = res.data
                            wx.setStorageSync('token', token)
                            wx.setStorageSync('user', user)
                            wx.showToast({
                                title: '登录成功',
                                icon: 'success',
                                duration: 2000,
                              })
                              fetch.getTopic({data:{}}).then(res=>{

                                  if (res.message == '已答题100道') {
                                    wx.reLaunch({
                                      url: `/pages/end/end`,
                                    })
                                  }else{
                                    wx.reLaunch({
                                        url: `/pages/exam/exam`,
                                      })
                                  }
                              })
                        }
                  
                    })
                
            
        }
    }

})